package com.geneqiao.jdbc.util;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class ObjectUtils
{
	private static final Integer QUERY_TIMEOUT = 5;

	private static boolean isEmpty(Object[] objects)
	{
		if (objects == null)
			return true;
		if (objects.length == 0)
			return true;
		if (objects[0] == null)
			return true;
		if (objects[0].toString() == "null")
			return true;
		return false;
	}

	public static ResultSet buildResultSet(Connection conn, String sql, Object[] objects) throws SQLException
	{
		if (isEmpty(objects))
		{
			Statement st = conn.createStatement();
			st.setQueryTimeout(QUERY_TIMEOUT);
			return st.executeQuery(sql);
		}
		PreparedStatement ps = conn.prepareStatement(sql);
		for (int i = 1; i < objects.length + 1; i++)
		{
			ps.setObject(i, objects[i - 1]);
		}
		ps.setQueryTimeout(QUERY_TIMEOUT);
		return ps.executeQuery();
	}

	public static PreparedStatement buildStatement(Connection conn, Map<Integer, Object> map) throws SQLException
	{
		return buildStatement(conn, map, false);
	}

	public static PreparedStatement buildStatement(Connection conn, Map<Integer, Object> map, boolean hasGenerageKey)
			throws SQLException
	{
		PreparedStatement ps;
		if (hasGenerageKey)
			ps = conn.prepareStatement(map.get(0).toString(), Statement.RETURN_GENERATED_KEYS);
		else
			ps = conn.prepareStatement(map.get(0).toString());
		ps.setQueryTimeout(QUERY_TIMEOUT);
		map.remove(0);
		Set<Entry<Integer, Object>> entries = map.entrySet();
		for (Entry<Integer, Object> entry : entries)
		{
			ps.setObject(entry.getKey(), entry.getValue());
		}
		return ps;
	}

	public static CallableStatement buildStatement(Connection conn, String sql) throws SQLException
	{
		return conn.prepareCall(sql);
	}

	public static Integer executeUpdate(Connection conn, String sql, Object[] objects) throws SQLException
	{
		int num;
		if (isEmpty(objects))
		{
			Statement st = conn.createStatement();
			st.setQueryTimeout(QUERY_TIMEOUT);
			num = st.executeUpdate(sql);
			st.close();
			return num;
		}
		PreparedStatement ps = conn.prepareStatement(sql);
		for (int i = 1; i < objects.length + 1; i++)
		{
			ps.setObject(i, objects[i - 1]);
		}
		ps.setQueryTimeout(QUERY_TIMEOUT);
		num = ps.executeUpdate();
		ps.close();
		return num;
	}
}
